#!/bin/bash
# ======================================
# 定时任务部署脚本（支持多环境）
# 使用方法:
#   bash deploy-cronjobs.sh worker   # 部署到worker环境
#   bash deploy-cronjobs.sh show     # 部署到show环境
# ======================================

set -e

ENV=$1

if [ -z "$ENV" ]; then
    echo "❌ 错误: 未指定环境"
    echo "用法: bash deploy-cronjobs.sh <环境名>"
    echo "支持的环境: worker, show"
    exit 1
fi

if [ "$ENV" != "worker" ] && [ "$ENV" != "show" ]; then
    echo "❌ 错误: 不支持的环境 '$ENV'"
    echo "支持的环境: worker, show"
    exit 1
fi

echo "=========================================="
echo "📦 开始部署定时任务到 $ENV 环境"
echo "=========================================="

# 设置服务器IP
if [ "$ENV" == "worker" ]; then
    SERVER_IP="39.101.74.188"
    echo "🌍 目标服务器: $SERVER_IP (Worker-ECS)"
elif [ "$ENV" == "show" ]; then
    SERVER_IP="8.145.38.110"
    echo "🌍 目标服务器: $SERVER_IP (Show-ECS)"
fi

# 1. 构建镜像
echo ""
echo "1️⃣ 构建 Docker 镜像..."
docker build --no-cache -t localhost/python-app:1.0.0 .
docker save -o python-app-1.0.0.tar localhost/python-app:1.0.0
echo "✅ 镜像构建完成"

# 2. 上传镜像到服务器
echo ""
echo "2️⃣ 上传镜像到 $ENV 服务器..."
scp python-app-1.0.0.tar root@$SERVER_IP:/tmp/
echo "✅ 镜像上传完成"

# 3. 获取Worker节点主机名并导入镜像
echo ""
echo "3️⃣ 查询Worker节点并导入镜像..."
WORKER_NODE=$(ssh root@$SERVER_IP "kubectl get nodes --no-headers | grep -v master | awk '{print \$1}' | head -1")
WORKER_IP=$(ssh root@$SERVER_IP "kubectl get node $WORKER_NODE -o jsonpath='{.status.addresses[?(@.type==\"InternalIP\")].address}'")

echo "   Worker节点: $WORKER_NODE ($WORKER_IP)"

# 转发镜像到Worker节点
ssh root@$SERVER_IP "scp /tmp/python-app-1.0.0.tar root@$WORKER_IP:/tmp/"

# 在Worker节点导入镜像
ssh root@$WORKER_IP "k3s ctr images import /tmp/python-app-1.0.0.tar"
echo "✅ 镜像导入完成"

# 4. 使用Kustomize生成并应用配置
echo ""
echo "4️⃣ 使用 Kustomize 部署配置..."

# 本地生成最终YAML
kubectl kustomize task/k8s/overlays/$ENV > /tmp/cronjobs-$ENV.yaml

# 上传到服务器
scp /tmp/cronjobs-$ENV.yaml root@$SERVER_IP:/tmp/

# 应用配置
ssh root@$SERVER_IP "kubectl apply -f /tmp/cronjobs-$ENV.yaml"
echo "✅ 配置部署完成"

# 5. 验证部署
echo ""
echo "5️⃣ 验证部署..."
ssh root@$SERVER_IP "kubectl get cronjobs -n tasks -o wide"

echo ""
echo "=========================================="
echo "✅ 定时任务已成功部署到 $ENV 环境"
echo "=========================================="
echo ""
echo "📋 后续操作:"
echo "   - 查看任务: ssh root@$SERVER_IP \"kubectl get cronjobs -n tasks\""
echo "   - 手动测试: ssh root@$SERVER_IP \"kubectl create job test-\$(date +%s) --from=cronjob/daily-tasks -n tasks\""
echo "   - 查看日志: ssh root@$SERVER_IP \"kubectl logs -n tasks -l app=daily-tasks --tail=100\""
